﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using NPOI.HSSF.UserModel;
using System.IO;
using System.Data;
using System.Diagnostics;

namespace DoubleH.Utility.IO
{
    public class ExcelTool : IFileIO
    {
        public const string ExtName = ".xls";

        string fileName = string.Empty;
        public string FileName
        {
            get { return fileName; }
            set { fileName = value; }
        }

        public DataTable ImportFileToDataTable()
        {
            if (string.IsNullOrEmpty(fileName))
                return null;

            DataTable data = new DataTable();
            int startRow = 0;
            try
            {
                FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
                IWorkbook workbook = null;
                if (fileName.IndexOf(".xlsx") > 0) // 2007版本以上
                    workbook = new XSSFWorkbook(fs);
                else if (fileName.IndexOf(".xls") > 0) // 2003版本以下
                    workbook = new HSSFWorkbook(fs);

                ISheet sheet = workbook.GetSheetAt(0);
                if (sheet != null)
                {
                    IRow firstRow = sheet.GetRow(0);
                    int cellCount = firstRow.LastCellNum; //一行最后一个cell的编号 即总的列数

                    //if (isFirstRowColumn)
                    //{
                    for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
                    {
                        ICell cell = firstRow.GetCell(i);
                        if (cell != null)
                        {
                            string cellValue = cell.StringCellValue;
                            if (cellValue != null)
                            {
                                DataColumn column = new DataColumn(cellValue);
                                data.Columns.Add(column);
                            }
                        }
                    }
                    startRow = sheet.FirstRowNum + 1;
                    //}
                    //else
                    //    startRow = sheet.FirstRowNum;

                    //最后一列的标号
                    int rowCount = sheet.LastRowNum;
                    for (int i = startRow; i <= rowCount; ++i)
                    {
                        IRow row = sheet.GetRow(i);
                        if (row == null) continue; //没有数据的行默认是null　　　　　　　

                        DataRow dataRow = data.NewRow();
                        for (int j = row.FirstCellNum; j < cellCount; ++j)
                        {
                            if (row.GetCell(j) != null) //同理，没有数据的单元格都默认是null
                                dataRow[j] = row.GetCell(j).ToString();
                        }
                        data.Rows.Add(dataRow);
                    }
                }
                return data;
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception: " + ex.Message);
                return null;
            }
        }

        public void ExportData(DataTable dataTable)
        {
        }

        public void ExportDataGridToFile(UC.DataGridExt grid)
        {
            int columnLenght = grid.Columns.Count;
            HSSFWorkbook hssfworkbook = new HSSFWorkbook();
            // 新建一个Excel页签
            ISheet sheet1 = hssfworkbook.CreateSheet("Sheet1");
            //先获取标题
            IRow rowHeader = sheet1.CreateRow(0);
            for (var j = 0; j < columnLenght; j++)
                CreateCell(rowHeader, j,(grid.Columns[j].Header==null?"": grid.Columns[j].Header.ToString()));
      
            //内容
            for (int i = 0; i < grid.Items.Count; i++)
            {
                IRow row1 = sheet1.CreateRow(i + 1);
                for (var j = 0; j < columnLenght; j++)
                {
                    System.Windows.Controls.DataGridCell cell= grid.GetCell(i, j);
                    if(cell==null)
                        continue;

                    System.Windows.Controls.TextBlock tb =cell.Content as System.Windows.Controls.TextBlock;
                    CreateCell(row1, j, (tb == null ? "" : tb.Text));
                }
            }

            FileStream fs = new FileStream(fileName, FileMode.Create);
            hssfworkbook.Write(fs);
            fs.Close();
        }

        private void CreateCell(IRow row, int columnIndex, string cellValue)
        {
            ICell cell = row.CreateCell(columnIndex);
            cell.SetCellValue(cellValue);
        }
    }
}